package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.utils.AgeCalculator;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住功能Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住功能
     *
     * @param id 入住功能主键
     * @return 入住功能
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住功能列表
     *
     * @param checkIn 入住功能
     * @return 入住功能
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住功能
     *
     * @param checkIn 入住功能
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住功能
     *
     * @param checkIn 入住功能
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住功能
     *
     * @param ids 需要删除的入住功能主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住功能信息
     *
     * @param id 入住功能主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInDto
     * @return
     */
    @Transactional
    @Override
    public int apply(CheckInApplyDto checkInDto) {
        //通过老人查询老人表中的 身份证以及状态来判断老人是否已入住  --单表查询可以用到mp
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1)
        );

        //是已入住则查询出来的数据不为空，直接结束方法
        if (elder != null) {
            throw new RuntimeException("该老人已入住");
        }
        //否则查询数据为空则需要添加数据，
        //1.更新床位状态为已入住
        Bed bed = bedMapper.selectOne(Wrappers.<Bed>lambdaQuery().eq(Bed::getId, checkInDto.getCheckInConfigDto().getBedId()));
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //2.新增或者更新老人表数据
        elder = insertOrUpdate(checkInDto, bed);
        //3.新增签约合同表数据
        insertContract(checkInDto, elder);
        //4.新增入住信息表数据
        CheckIn checkIn = insertCheckIn(checkInDto, elder);
        //5.新增入住配置表数据
        insertCheckInConfig(checkIn, checkInDto);
        return 1;
    }

    @Override
    @Transactional
    public CheckInDetailVo selectDetail(Long id) throws JsonProcessingException {
        //根据老人id查询老人表,将elder对象封装成vo返回给前端
        Elder elder = elderMapper.selectById(id);
        int age = AgeCalculator.calculateAge(elder.getIdCardNo());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        checkInElderVo.setAge(age);
        //根据老人id查询合同表数据，将合同对象封装成vo返回给前端
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        LocalDateTime startDate = contract.getStartDate();
        LocalDateTime endDate = contract.getEndDate();

        CheckIn checkIn = checkInMapper.selectOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getElderId, id));
        //根据入住表查询数据可以得到入住表id，基于入住表id可以查询对应入住配置配置表的数据
        Long checkInId = checkIn.getId();
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkInId));
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //这里不用拷贝contract直接封装
        checkInDetailVo.setContract(contract);
        //属性拷贝elder-->checkInElderVo
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //属性拷贝checkInConfig-->checkInConfigVo
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        String bedNumber = checkIn.getBedNumber();
        checkInConfigVo.setStartDate(startDate);
        checkInConfigVo.setEndDate(endDate);
        checkInConfigVo.setBedNumber(bedNumber);
        checkInConfigVo.setFeeStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setFeeEndDate(checkInConfig.getFeeEndDate());

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        String remark = checkIn.getRemark();
        // 直接转换为List
        ObjectMapper mapper = new ObjectMapper();

        List<ElderFamilyVo> contactList = mapper.readValue(
                remark,
                new TypeReference<List<ElderFamilyVo>>() {
                }
        );

        checkInDetailVo.setElderFamilyVoList(contactList);

        return checkInDetailVo;
    }

    //5.新增入住配置表数据
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInDto) {
        CheckInConfigDto checkInConfigDto = checkInDto.getCheckInConfigDto();
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }


    private void insertContract(CheckInApplyDto checkInDto, Elder elder) {
        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(checkInDto.getCheckInContractDto(), contract);
        String generateContractNumber = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(generateContractNumber);
        contract.setElderId(Integer.valueOf(elder.getId() + ""));
        contract.setElderName(elder.getName());
        LocalDateTime checkInStartTime = checkInDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        boolean before = checkInStartTime.isBefore(LocalDateTime.now());
        Integer status = before ? 1 : 0;
        contract.setStatus(status);
        contractMapper.insert(contract);
    }


    //4.新增入住信息表数据
    private CheckIn insertCheckIn(CheckInApplyDto checkInDto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;

    }

    //2.新增或者更新老人表数据
    private Elder insertOrUpdate(CheckInApplyDto checkInDto, Bed bed) {
        CheckInElderDto checkInElderDto = checkInDto.getCheckInElderDto();
        Elder newElder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, newElder);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setStatus(1);
        //新增和更新的判断依据是：
        // 查询老人表中的存在的身份证编号和不等于状态1的时候 有数据 才需要修改
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInDto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus, 1));
        if (oldElder != null) {
            //修改
            elderMapper.updateById(newElder);
        } else {
            // 没有数据，则是新增
            elderMapper.insert(newElder);
        }
        return newElder;
    }
}
